package com.bsoft.advance.client.transport;

import com.alibaba.fastjson.JSON;
import com.bsoft.advance.core.common.RpcRequest;
import com.bsoft.advance.core.common.RpcResponse;
import com.bsoft.advance.core.protocol.MessageHeader;
import com.bsoft.advance.core.protocol.MessageProtocol;
import com.bsoft.advance.core.protocol.MsgType;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 客户端消息响应处理类
 */
@Slf4j
@ChannelHandler.Sharable
public class RpcResponseHandler extends SimpleChannelInboundHandler<MessageProtocol<RpcResponse>> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol<RpcResponse> protocol) throws Exception {
        MessageHeader header = protocol.getHeader();
        switch (MsgType.findByType(header.getMsgType())) {
            case RESPONSE:
                // 监听到服务端的响应，缓存栅栏可以解除，让future获取结果
                log.info("got response from server：{}", JSON.toJSONString(protocol));
                UnsolvedResponseCache.complete(protocol);
                break;
            case HEARTBEAT_RESPONSE:
                // 心跳处理
                log.info("server [{}] is heartbeat : {}", ctx.channel().remoteAddress().toString().substring(1), protocol.getBody().getHeartbeat());
                break;
            default:
                break;
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("server [{}] is disconnected!", ctx.channel().remoteAddress().toString().substring(1));
        super.channelInactive(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 每空闲时间5s，要发送一次心跳给服务端
        if (evt instanceof IdleStateEvent) {
            // 读超时事件
            IdleState state = ((IdleStateEvent) evt).state();
            if (IdleState.WRITER_IDLE == state) {
                // 获取通道
                Channel channel = RpcTransportFactory.getDefaultTransportInstance().getChannel((InetSocketAddress) ctx.channel().remoteAddress());
                // 发送心跳给服务端
                MessageProtocol<RpcRequest> protocol = new MessageProtocol<>();
                protocol.setHeader(MessageHeader.buildHeartBeat(MsgType.HEARTBEAT_REQUEST));
                protocol.setBody(RpcRequest.buildHeartBeat());
                channel.writeAndFlush(protocol).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            }
        }else{
            super.userEventTriggered(ctx, evt);
        }
    }
}
